<?php
//CROP IMAGE USING GD
if (!empty($_GET['cropimage'])) {

    if (!extension_loaded('gd'))
        die('PHP GD extension not installed.');

    $src = $_GET['image'];
    $w = $_GET['width'];
    $h = $_GET['height'];
    $x = $_GET['x'];
    $y = $_GET['y'];

    if (strpos($_GET['image'], "library/pngs") !== 0)
        die('Invalid image.');
    if ($_GET['width'] > 10000)
        die('Invalid input.');
    if ($_GET['height'] > 10000)
        die('Invalid input.');
    if ($_GET['x'] < 0 || $_GET['x'] > 10000)
        die('Invalid input.');
    if ($_GET['y'] < 0 || $_GET['y'] > 10000)
        die('Invalid input.');

    $img_r = imagecreatefrompng($src);
    $dst_r = imagecreatetruecolor($w, $h);

    imagecopy($dst_r, $img_r, 0, 0, $x, $y, $w, $h);

    header('Content-type: image/png');
    header("Content-Disposition: attachment; filename=image.png");
    header("Pragma: no-cache");
    header("Expires: 0");

    imagepng($dst_r, null, 9);

    die();
}

include_once 'data.php';
include_once 'functions.php';
session_write_close();

$pdf_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'library';
$png_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'pngs';

if (!empty($_GET['file'])) {
    $file = preg_replace('/[^a-zA-z0-9\_\.pdf]/', '', $_GET['file']);
    if (substr($_GET['file'], 0, 4) == 'lib_') {
        $pdf_path = $temp_dir;
    }
} else {
    die('Error! PDF does not exist.');
}

$page = 1;
if (isset($_GET['page']))
    $page = intval($_GET['page']);

if (file_exists($pdf_path . DIRECTORY_SEPARATOR . $file)) {
    exec(select_pdfinfo() . '"' . $pdf_path . DIRECTORY_SEPARATOR . $file . '"', $output);
    $output = implode('#', $output);
    $page_number = preg_replace('/(.*#Pages:\s+)(\d+)(#.*)/', '$2', $output);
    if ($page > $page_number)
        $page = $page_number;
    if (empty($page_number))
        die('Error! Program pdfinfo not functional.');
}

if (isset($_GET['renderpdf'])) {

    if (file_exists($pdf_path . DIRECTORY_SEPARATOR . $file)) {

        if (!file_exists($png_path . DIRECTORY_SEPARATOR . $file . '.' . $page . '.png')
                || filemtime($png_path . DIRECTORY_SEPARATOR . $file . '.' . $page . '.png') < filemtime($pdf_path . DIRECTORY_SEPARATOR . $file)) {
            exec(select_ghostscript() . " -dSAFER -sDEVICE=png16m -r150 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dDOINTERPOLATE -dFirstPage=" . $page . " -dLastPage=" . $page . " -o \"" . $png_path . DIRECTORY_SEPARATOR . $file . "." . $page . ".png\" \"" . $pdf_path . DIRECTORY_SEPARATOR . $file . "\"");
        }
        if (file_exists($png_path . DIRECTORY_SEPARATOR . $file . "." . $page . ".png")) {
            $img_size_array = getimagesize('library' . DIRECTORY_SEPARATOR . 'pngs' . DIRECTORY_SEPARATOR . $file . "." . $page . ".png");
            print $img_size_array[0];
        } else {
            die('Program Ghostscript not functional.');
        }
    } else {
        die('PDF does not exist.');
    }
    die();
}

if (isset($_GET['renderthumbs'])) {

    if (file_exists($pdf_path . DIRECTORY_SEPARATOR . $file)) {

        if (!file_exists($png_path . DIRECTORY_SEPARATOR . $file . ".t1.png")
                || filemtime($png_path . DIRECTORY_SEPARATOR . $file . '.t1.png') < filemtime($pdf_path . DIRECTORY_SEPARATOR . $file)) {
            exec(select_ghostscript() . " -dSAFER -sDEVICE=png16m -r15 -dTextAlphaBits=1 -dGraphicsAlphaBits=1 -o \"" . $png_path . DIRECTORY_SEPARATOR . $file . ".t%d.png\" \"" . $pdf_path . DIRECTORY_SEPARATOR . $file . "\"");
        }
    }
    die();
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>I, Librarian 2.2 - PDF Viewer</title>
        <link type="text/css" href="css/custom-theme/jquery-ui-custom.css" rel="stylesheet">
        <link type="text/css" href="css/static.css" rel="stylesheet">
        <link type="text/css" href="css/tipsy.css" rel="stylesheet">
        <link type="text/css" href="css/jquery.jgrowl.css" rel="stylesheet">
        <link type="text/css" href="css/jquery.Jcrop.css" rel="stylesheet">
        <style type="text/css">
<?php include_once 'style.php'; ?>
            @media print
            {
                #pdf-viewer-controls, #thumbs {display: none}
                #pdf-viewer-img {display:inline}
            }
            @page {
                margin: 0;
            }
        </style>
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/jquery-ui-custom.min.js"></script>
        <script type="text/javascript" src="js/jquery.tipsy.js"></script>
        <script type="text/javascript" src="js/jquery.clicknscroll.min.js"></script>
        <script type="text/javascript" src="js/jquery.jgrowl.js"></script>
        <script type="text/javascript" src="js/jquery.Jcrop.min.js"></script>
    </head>
    <body class="alternating_row" style="padding:0;margin:0;border:0;overflow:hidden">
        <div style="width:100%;height:30px<?php if (isset($_GET['toolbar']) && $_GET['toolbar'] == 0) print ';display:none'; ?>" id="pdf-viewer-controls">
            <div style="float:left;padding:4px;line-height:22px">
                <button id="toggle">Toggle Page Previews</button>
                <button id="save">Save PDF</button>
                <button id="print">Print Page</button>
                <button id="size1" title="Actual size">100%</button>
                <button id="size2">Fit the page width</button>
                <button id="size3">Fit the page height</button>
            </div>
            <div style="float:left;padding-left:4px;padding-top:8px;line-height:22px">
                <div id="zoom"></div><span style="position:relative;top:-4px;"></span>
            </div>
            <div style="float:left;padding:4px;line-height:22px">
                <button id="control-first">First Page</button>
                <button id="control-prev">Previous Page</button>
                <input type="text" id="control-page" size="3" value="<?php print $page ?>"> / <?php print $page_number ?>
                <button id="control-next">Next Page</button>
                <button id="control-last">Last Page</button>
                <input type="text" id="pdf-viewer-search" size="10" value="" placeholder="Find" style="width:100px"
                       title="Use &lt;?&gt; as single-letter, and &lt;*&gt; as multi-letter wildcards">
                <button id="pdf-viewer-clear">Clear</button>
                <button id="pdf-viewer-copy-image" <?php if (!extension_loaded('gd')) print 'disabled' ?>>Copy image</button>
            </div>
        </div>
        <div id="pdf-viewer-div">
            <div id="thumbs"<?php if (isset($_GET['navpanes']) && $_GET['navpanes'] == 0) print ' style="display:none"'; ?>></div>
            <div id="pdf-viewer-img-div">
                <img src="" id="pdf-viewer-img" alt="">
                <div id="pdf-viewer-loader" class="ui-corner-all" style="display:none">
                    <img src="img/ajaxloader2.gif" alt=""> Rendering PDF
                </div>
                <div id="highlight-container"></div>
            </div>
        </div>
        <div id="copy-image-container" title="Select an area to copy and press the Copy button" style="display:none">
            <img src="" id="image-to-copy" style="box-shadow:0 0 2px #333">
            <form action="viewpdf.php" method="get">
                <input type="hidden" name="cropimage" value="1">
                <input type="hidden" name="image" id="image-src" value="">
                <input type="hidden" id="x" name="x">
                <input type="hidden" id="y" name="y">
                <input type="hidden" id="w" name="width">
                <input type="hidden" id="h" name="height">
            </form>
        </div>
        <script type="text/javascript">
            <!--
    var fileName='<?php print $file ?>',totalPages=<?php print $page_number ?>,navpanes=true;
    <?php if (isset($_GET['navpanes']) && $_GET['navpanes'] == 0) print 'navpanes=false;'; ?>
    $.ajaxSetup({cache: false});
    if (!$.browser.msie) $('#pdf-viewer-img-div').clickNScroll({allowThrowing:false,acceleration:1});
    $('#save').button({
        icons: {
            primary: "ui-icon-disk"
        },
        text: false
    }).click(function(){
        window.location.assign('downloadpdf.php?file='+fileName);
        return false;
    }).tipsy({fade:true});
    $('#print').button({
        icons: {
            primary: "ui-icon-print"
        },
        text: false
    }).click(function(){
        window.print();
    }).tipsy({fade:true});
    $('#size1').button({
        icons: {
            primary: "ui-icon-zoomin"
        }
    }).tipsy({fade:true});
    $('#size2').button({
        icons: {
            primary: "ui-icon-arrowthickstop-1-w",
            secondary: "ui-icon-arrowthickstop-1-e"
        },
        text: false
    }).tipsy({fade:true});
    $('#size3').button({
        icons: {
            primary: "ui-icon-document",
            secondary: "ui-icon-arrowthick-2-n-s"
        },
        text: false
    }).tipsy({fade:true});
    $('#control-first').button({
        icons: {
            primary: "ui-icon-arrowthickstop-1-n"
        },
        text: false
    }).tipsy({fade:true});
    $('#control-prev').button({
        icons: {
            primary: "ui-icon-arrowthick-1-n"
        },
        text: false
    }).tipsy({fade:true});
    $('#control-next').button({
        icons: {
            primary: "ui-icon-arrowthick-1-s"
        },
        text: false
    }).tipsy({fade:true});
    $('#control-last').button({
        icons: {
            primary: "ui-icon-arrowthickstop-1-s"
        },
        text: false
    }).tipsy({fade:true});
    $('#pdf-viewer-copy-image').button({
        icons: {
            primary: "ui-icon-image"
        },
        text: false
    }).click(function(){
        $('#image-to-copy').attr('src',$('#pdf-viewer-img').attr('src'));
        $('#image-src').val($('#pdf-viewer-img').attr('src'));
        $('#copy-image-container').dialog({
            autoOpen: true,
            modal: true,
            width: $(window).width()-40,
            height: $(window).height()-40,
            buttons: {
                'Copy': function() {
                    $('#copy-image-container form').submit();
                },
                'Close': function() {
                    $.Jcrop('#image-to-copy').destroy();
                    $('.jcrop-holder').remove();
                    $(this).dialog('destroy');
                }
            },
            open: function(){
                $('#image-to-copy').Jcrop({
                    onSelect: function(c){
                        $('#x').val(c.x);
                        $('#y').val(c.y);
                        $('#w').val(c.w);
                        $('#h').val(c.h);
                    }
                });
            },
            close: function(){
                $.Jcrop('#image-to-copy').destroy();
                $('.jcrop-holder').remove();
                $(this).dialog('destroy');
            }
        });
    }).tipsy({fade:true});
    //INITIAL WINDOW SIZE
    var wh=$(window).height(),toolbar=31,navw=160,ww=$('body').width();
    if($('#pdf-viewer-controls').is(':hidden')) toolbar=0;
    if(!navpanes) navw=0;
    $('#pdf-viewer-div').height(wh-toolbar).width(ww);
    if ($.browser.msie && $.browser.version < 9) {
        ww=ww-3;
        $('#pdf-viewer-img-div').css('width',ww-navw);
    } else {
        $('#pdf-viewer-img-div').css('width','auto');
    }
    //WINDOW RESIZE
    $(window).resize(function(){
        var wh=$(window).height(),toolbar=31,navw=160,ww=$('body').width();
        if($('#pdf-viewer-controls').is(':hidden')) toolbar=0;
        $('#pdf-viewer-div').height(wh-toolbar).width(ww);
        if(!navpanes) navw=0;
        if($('#thumbs').is(':visible')) ww=ww-navw;
        if ($.browser.msie && $.browser.version < 9) {
            ww=ww-3;
            $('#pdf-viewer-img-div').css('width',ww);
        } else {
            $('#pdf-viewer-img-div').css('width','auto');
        }
        var iw=$('#pdf-viewer-img').width(),riw=$('#pdf-viewer-img').data('riw'),piw=Math.round(100*iw/riw);
        $('#zoom').slider("value",piw);
        $('#zoom').next().text(piw+'%');
        var h=$('#pdf-viewer-img').height(),pos=$('#pdf-viewer-img').position();
        $('#highlight-container').css({'width':iw,'height':h,'left':Math.max(pos.left,0)});
    });
    $('#toggle').button({
        icons: {
            primary: "ui-icon-bookmark"
        },
        text: false
    }).click(function(){
        if($('#thumbs').is(':visible')) {
            $('#thumbs').hide();
            $('#pdf-viewer-img-div').css('width','auto');
        } else
            if($('#thumbs').is(':hidden')) {
                if($('#thumbs').html()=='') {
                    $.get('viewpdf.php?renderthumbs=1&file='+fileName, function() {
                        var thumbs='',i=1;
                        while (i<=totalPages) {
                            thumbs = thumbs+'<p>Page '+i+':<br><img class="pdf-viewer-thumbs thumb-'+i+'" src="library/pngs/'+fileName+'.t'+i+'.png" alt=""></p>';
                            i++;
                        }
                        $('#thumbs').html(thumbs);
                    });
            }
            $('#thumbs').show();
            $('#pdf-viewer-img-div').css('width','auto');
        }
        var iw=$('#pdf-viewer-img').width(),riw=$('#pdf-viewer-img').data('riw'),piw=Math.round(100*iw/riw);
        $('#zoom').slider("value",piw);
        $('#zoom').next().text(piw+'%');
        var ih=$('#pdf-viewer-img').height(),pos=$('#pdf-viewer-img').position();
        $('#highlight-container').css({'width':iw+'px','height':ih+'px','left':Math.max(pos.left,0)+'px'});
    }).tipsy({fade:true,gravity:'nw'});
    //ZOOM
    $('#size1').click(function(){
        $('#pdf-viewer-img-div').scrollTop(0).scrollLeft(0);
        $('#pdf-viewer-img').css('width','auto').css('height','auto');
        $('#zoom').slider("value",100);
        $('#zoom').next().text('100%');
        var w=$('#pdf-viewer-img').width(),h=$('#pdf-viewer-img').height(),pos=$('#pdf-viewer-img').position();
        $('#highlight-container').css({'width':w,'height':h,'left':Math.max(pos.left,0)});
    });
    $('#size2').click(function(){
        $('#pdf-viewer-img-div').scrollTop(0).scrollLeft(0);
        $('#pdf-viewer-img').css('width','99%').css('height','auto');
        var iw=$('#pdf-viewer-img').width(),riw=$('#pdf-viewer-img').data('riw'),piw=Math.round(100*iw/riw);
        $('#zoom').slider("value",piw);
        $('#zoom').next().text(piw+'%');
        var w=$('#pdf-viewer-img').width(),h=$('#pdf-viewer-img').height(),pos=$('#pdf-viewer-img').position();
        $('#highlight-container').css({'width':w,'height':h,'left':Math.max(pos.left,0)});
    });
    $('#size3').click(function(){
        $('#pdf-viewer-img-div').css('overflow','hidden').scrollTop(0).scrollLeft(0);
        $('#pdf-viewer-img').css({'height':'99%','width':'auto'});
        var iw=$('#pdf-viewer-img').width(),riw=$('#pdf-viewer-img').data('riw'),piw=Math.round(100*iw/riw);
        $('#zoom').slider("value",piw);
        $('#zoom').next().text(piw+'%');
        var ih=$('#pdf-viewer-img').height(),pos=$('#pdf-viewer-img').position();
        $('#highlight-container').css({'width':iw+'px','height':ih+'px','left':Math.max(pos.left,0)+'px'});
        $('#pdf-viewer-img-div').css('overflow','auto');
    });
    $('#zoom').slider({
        min: 30,
        value: 100,
        slide: function(e,ui) {
            var riw=$('#pdf-viewer-img').data('riw'),iw=Math.round(ui.value*riw/100);
            $('#pdf-viewer-img').css('width',iw).css('height','auto');
            $(this).next().text(ui.value+'%');
            var ih=$('#pdf-viewer-img').height(),pos=$('#pdf-viewer-img').position();
            $('#highlight-container').css({'width':iw+'px','height':ih+'px','left':Math.max(pos.left,0)+'px'});
        }
    });
    //OPEN FIRST PAGE AND THUMBS
    $('body').data('lock',1);
    $('#pdf-viewer-loader').fadeIn(800);
    $.get('viewpdf.php?renderpdf=1&file='+fileName+'&page=1', function(riw) {
        if(isNaN(riw)) {
            $.jGrowl(riw,{theme:'jgrowl-error'});
            $('body').data('lock',0);
            $('#pdf-viewer-loader').hide();
            return false;
        }
        $('#pdf-viewer-loader').hide();
        $('#pdf-viewer-img').attr('src','library/pngs/'+fileName+'.1.png').show().data('pg',1);
        $('#control-page').val('1');
        $('body').data('lock',0);
        var iw=$('#pdf-viewer-img').width(),piw=Math.round(100*iw/riw);
        $('#pdf-viewer-img').data('riw',riw);
        $('#zoom').slider( "value" , piw );
        $('#zoom').next().text(piw+'%');
        if(navpanes) {
            $.get('viewpdf.php?renderthumbs=1&file='+fileName, function() {
                var thumbs='',i=1;
                while (i<=totalPages) {
                    thumbs = thumbs+'<p>Page '+i+':<br><img class="pdf-viewer-thumbs thumb-'+i+'" src="library/pngs/'+fileName+'.t'+i+'.png" alt=""></p>';
                    i++;
                }
                $('#thumbs').html(thumbs);
            });
        }
    });
    //PAGE NAVIGATION
    function fetch_page(file,pg) {
        $('body').data('lock',1);
        $('#pdf-viewer-img').data('pg',pg);
        var loader=function(){$('#pdf-viewer-loader').fadeIn(400)};
        var timeid=setTimeout(loader,500);
        $.get('viewpdf.php?renderpdf=1&file='+file+'&page='+pg, function(answer) {
            clearTimeout(timeid);
            $('#pdf-viewer-loader').stop(true,true).hide();
            $('#pdf-viewer-img').attr('src','library/pngs/'+file+'.'+pg+'.png');
            $('#pdf-viewer-img-div').scrollTop(0).scrollLeft(0);
            $('#control-page').val(pg);
            $('.pdfviewer-highlight').hide();
            $('.highlight-page-'+pg).fadeTo(400,0.25);
            $('body').data('lock',0);
        });
    }
    $('#control-first').click(function(){
        if($('body').data('lock')==1) return false;
        if($('#pdf-viewer-img').data('pg')==1) return false;
        fetch_page(fileName,1);
    });
    $('#control-prev').click(function(){
        if($('body').data('lock')==1) return false;
        var pg=$('#pdf-viewer-img').data('pg');
        if(pg==1) return false;
        pg=pg-1;
        pg=Math.max(pg,1);
        fetch_page(fileName,pg);
    });
    $('#control-next').click(function(){
        if($('body').data('lock')==1) return false;
        var pg=$('#pdf-viewer-img').data('pg');
        if(pg==totalPages) return false;
        pg=pg+1;
        pg=Math.min(pg,totalPages);
        fetch_page(fileName,pg);
    });
    $('#control-last').click(function(){
        if($('body').data('lock')==1) return false;
        if($('#pdf-viewer-img').data('pg')==totalPages) return false;
        fetch_page(fileName,totalPages);
    });
    $('#control-page').keydown(function(e){
        if($('body').data('lock')==1) return false;
        if(e.which!=13) return true;
        var pg=parseInt($(this).val());
        if(isNaN(pg) || pg<1 || pg > totalPages) {
             $(this).val('1');
             pg=1;
        }
        fetch_page(fileName,pg);
    }).focus(function(){
        this.select();
    });
    $('#thumbs').click(function(e){
        var $t=$(e.target),pg=$('#thumbs img').index($t)+1,currpg=$('#pdf-viewer-img').data('pg');
        if(!$t.is('img') || pg==currpg) return false;
        if($('body').data('lock')==1) return false;
        fetch_page(fileName,pg);
    });
    //SEARCH
    $('#pdf-viewer-search').keydown(function(e){
        if(e.which!=13) return true;
        e.preventDefault();
        var st=$('#pdf-viewer-search').val();
        $('.pdfviewer-highlight').remove();
        if(st==''){
            $('#pdf-viewer-clear').click();
            return false;
        }
        $('body').data('lock',1);
        $.getJSON('searchpdf.php', {'search_term': st , 'file': fileName},function(answer){
            if(jQuery.isEmptyObject(answer)) {
                $.jGrowl('No Hits.');
                $('body').data('lock',0);
                return false;
            }
            if(answer['Error']!=undefined) {
                $.jGrowl(answer['Error'],{theme:'jgrowl-error'});
                $('body').data('lock',0);
                return false;
            }
            $('#thumbs').show();
            var i=0,positions=new Array(),pgs=[],w=$('#pdf-viewer-img').width(),h=$('#pdf-viewer-img').height(),pos=$('#pdf-viewer-img').position();
            $('#highlight-container').css('left',Math.max(pos.left,0)).width(w).height(h);
            $.each(answer, function(key, rows) {
                pgs[i] = key;
                i=i+1;
                positions[key]=new Array();
                $.each(rows, function(key2, row) {
                    $('#highlight-container').append('<div class="ui-corner-all pdfviewer-highlight highlight-page-'+key+'" id="highlight-page-'+key+'-row-'+key2+'">&nbsp;</div>');
                    $('#highlight-page-'+key+'-row-'+key2).css({'width': row.width +'%','height': row.height +'%','top': row.top +'%','left': row.left +'%'});
                    positions[key][key2]=row.top;
                });
            });
            var openpg=Math.min.apply(Math,pgs),firstH=Math.min.apply(Math,positions[openpg]);
            $('#pdf-viewer-img').data('pg',openpg);
            var loader=function(){$('#pdf-viewer-loader').fadeIn(400)};
            var timeid=setTimeout(loader,500);
            $.get('viewpdf.php?renderpdf=1&file='+fileName+'&page='+openpg, function() {
                clearTimeout(timeid);
                $('#pdf-viewer-loader').stop(true,true).hide();
                $('#pdf-viewer-img').attr('src','library/pngs/'+fileName+'.'+openpg+'.png');
                $('#pdf-viewer-img-div').scrollTop(-20+$('#pdf-viewer-img').height()*firstH/100).scrollLeft(0);
                $('#control-page').val(openpg);
                $('.highlight-page-'+openpg).fadeTo(400,0.25);
                $('body').data('lock',0);
            });
            if($('#thumbs').html()=='') {
                $.get('viewpdf.php?renderthumbs=1&file='+fileName, function() {
                    var thumbs='',i=1;
                    while (i<=totalPages) {
                        thumbs = thumbs+'<p>Page '+i+':<br><img class="pdf-viewer-thumbs thumb-'+i+'" src="library/pngs/'+fileName+'.t'+i+'.png" alt=""></p>';
                        i++;
                    }
                    $('#thumbs').html(thumbs);
                    $('.pdf-viewer-thumbs').addClass('ui-state-disabled');
                    $.each(pgs, function(key, pg) {
                        $('.thumb-'+pg).removeClass('ui-state-disabled');
                    });
                });
            } else {
                $('.pdf-viewer-thumbs').addClass('ui-state-disabled');
                $.each(pgs, function(key, pg) {
                    $('.thumb-'+pg).removeClass('ui-state-disabled');
                });
            }
        });
    }).focus(function(){
        this.select();
    }).tipsy({fade:true});
    $('#pdf-viewer-clear').button({
        icons: {
            primary: "ui-icon-arrowreturnthick-1-w"
        },
        text: false
    }).click(function(){
        $('#pdf-viewer-search').val('');
        $('.pdf-viewer-thumbs').removeClass('ui-state-disabled');
        $('.pdfviewer-highlight').remove();
        $('#highlight-container').css({'width':0,'height':0,'left':0});
    }).tipsy({fade:true});
    //-->
        </script>
    </body>
</html>